<template>
  <div>
    <h4 v-if="$route.query.type === 'user'">批量导入员工</h4>
    <h4 v-if="$route.query.type === 'money'">批量导入工资信息</h4>
    <!-- 使用上传Excel组件 -->
    <upload-excel :on-success="onSuccess" />
  </div>
</template>

<script>
import { importEmployeeAPi } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    // 读取Excel成功之后会调用
    onSuccess(excelData) {
      const { header, results } = excelData
      console.log(header)
      console.log(results)
      if (this.$route.query.type === 'user') {
        this.importUser(results)
      }
    },

    async importUser(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      results.forEach(item => {
        const userInfo = {}
        Object.keys(item).forEach(val => {
          if (['correctionTime', +'timeOfEntry'].includes(userRelations[val])) {
            userInfo[userRelations[val]] = this.formatDate(item[val], '/')
          } else {
            userInfo[userRelations[val]] = item[val]
          }
        })
        arr.push(userInfo)
      })
      //   发生请求
      await importEmployeeAPi(arr)
      // 提示
      this.$message.success('导入成功')
      // 返回之前界面
      this.$router.back()
      // console.log(arr)
    },

    // 格式化世间
    formatDate(numb, format) {
      // console.log(numb)
      // console.log(format)
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }

  }
}
</script>

<style>

</style>
